import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { ConfigService } from '@nestjs/config';
import { WinstonModule } from 'nest-winston';
import { join } from 'path';
import { AppModule } from './app.module';
import { logInstance } from './utils/log';
import { ValidationPipe } from './pipe/validation.pipe';
import { HttpExceptionFilter } from './filters/http-exception.filter';
import { ResponseInterceptor } from './interceptor/response.interceptor';

const prefix = 'api';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
    logger: WinstonModule.createLogger({ instance: logInstance }),
  });

  const configService = app.get<ConfigService>(ConfigService);
  app.setGlobalPrefix(prefix);

  // 跨域设置
  app.enableCors({
    origin: [
      'http://localhost:3000',
      'http://localhost:9001',
      'http://localhost:3002',
      'http://192.168.0.107:3002',
      'http://localhost:8080',
    ],
    credentials: true,
  });

  // 设置静态目录
  app.useStaticAssets(join(__dirname, '..', 'static'), {
    prefix: `/${prefix}`,
  });

  // 全局管道
  app.useGlobalPipes(new ValidationPipe());

  // 全局异常过滤器
  app.useGlobalFilters(new HttpExceptionFilter());

  // 全局拦截器
  app.useGlobalInterceptors(new ResponseInterceptor());

  const port = configService.get<number>('NODE_API_PORT') || 3002;

  await app.listen(port, '0.0.0.0', () => {
    console.log(`server is running: http://localhost:${port}/api`);
    console.log(`server is running: http://127.0.0.1:${port}/api`);
    console.log(`server is running: http://0.0.0.0:${port}/api`);
  });
}
bootstrap();
